"""
交易监控页面
提供实时交易监控、订单管理、持仓分析等功能
"""

import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional

from ..components.common import (
    create_sidebar_navigation, make_api_request,
    display_loading_spinner, show_success_message, show_error_message
)
from ..components.metrics import create_metric_card, create_status_indicator
from ..components.charts import create_line_chart, create_bar_chart, create_candlestick_chart
from ..components.tables import create_data_table, create_editable_table
from ..components.filters import create_date_filter, create_multiselect_filter
from ..services.data_service import DataService


# 初始化数据服务
@st.cache_resource
def get_data_service():
    """获取数据服务实例"""
    return DataService()


# 数据获取函数
@st.cache_data(ttl=30)  # 30秒缓存
def get_trading_overview():
    """获取交易概览数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_trading_data("overview")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取交易概览数据失败: {str(e)}")
    
    # 降级数据
    return {
        "today_trades": {"value": "25笔", "delta": "8"},
        "today_amount": {"value": "125.8万", "delta": "35.2万"},
        "today_pnl": {"value": "+12.5万", "delta": "8.3万"},
        "position_value": {"value": "485.2万", "delta": "15.6万"}
    }


@st.cache_data(ttl=60)  # 1分钟缓存
def get_watchlist_data():
    """获取重点关注股票数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_market_data("watchlist")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取关注股票数据失败: {str(e)}")
    
    # 降级数据
    return pd.DataFrame({
        '股票代码': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH', '000858.SZ'],
        '股票名称': ['平安银行', '万科A', '浦发银行', '招商银行', '五粮液'],
        '最新价': [12.50, 18.30, 8.90, 45.20, 168.50],
        '涨跌幅': ['+2.3%', '-1.2%', '+0.8%', '+1.5%', '+3.2%'],
        '成交量': ['2.5万手', '8.3万手', '1.2万手', '5.6万手', '3.8万手'],
        '持仓': ['1000股', '500股', '1200股', '300股', '100股'],
        '盈亏': ['+2300', '-1100', '+960', '+2030', '+5400'],
        '操作': ['监控中', '监控中', '监控中', '监控中', '监控中']
    })


@st.cache_data(ttl=30)  # 30秒缓存
def get_realtime_kline(symbol: str = "000001.SZ"):
    """获取实时K线数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_market_data("kline", {"symbol": symbol, "interval": "5m"})
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取K线数据失败: {str(e)}")
    
    # 降级数据
    dates = pd.date_range(start='09:30', end='11:30', freq='5min')
    return pd.DataFrame({
        '时间': dates,
        '开盘': [12.0 + i * 0.01 + np.random.normal(0, 0.1) for i in range(len(dates))],
        '最高': [12.1 + i * 0.01 + np.random.normal(0, 0.1) for i in range(len(dates))],
        '最低': [11.9 + i * 0.01 + np.random.normal(0, 0.1) for i in range(len(dates))],
        '收盘': [12.0 + i * 0.01 + np.random.normal(0, 0.1) for i in range(len(dates))],
        '成交量': [1000 + np.random.randint(0, 500) for _ in range(len(dates))]
    })


@st.cache_data(ttl=30)  # 30秒缓存
def get_realtime_pnl():
    """获取实时盈亏数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_trading_data("realtime_pnl")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取盈亏数据失败: {str(e)}")
    
    # 降级数据
    dates = pd.date_range(start='09:30', end='11:30', freq='5min')
    return pd.DataFrame({
        '时间': dates,
        '累计盈亏': [i * 100 + np.random.normal(0, 200) for i in range(len(dates))]
    })


@st.cache_data(ttl=60)  # 1分钟缓存
def get_trading_signals():
    """获取交易信号数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_strategy_data("signals")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取交易信号失败: {str(e)}")
    
    # 降级数据
    return pd.DataFrame({
        '时间': ['10:30:15', '10:28:42', '10:31:05', '10:25:30', '10:32:18'],
        '股票': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH', '000858.SZ'],
        '策略': ['均线策略', '动量策略', '网格交易', '均线策略', '趋势跟踪'],
        '信号': ['买入', '卖出', '网格买入', '买入', '持有'],
        '价格': [12.50, 18.30, 8.90, 45.20, 168.50],
        '数量': [1000, 500, 1200, 300, 100],
        '状态': ['已执行', '已执行', '执行中', '待执行', '监控中']
    })


@st.cache_data(ttl=120)  # 2分钟缓存
def get_orders_data():
    """获取订单数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_trading_data("orders")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取订单数据失败: {str(e)}")
    
    # 降级数据
    return pd.DataFrame({
        '订单号': ['ORD001', 'ORD002', 'ORD003', 'ORD004', 'ORD005'],
        '时间': ['10:30:15', '10:28:42', '10:31:05', '10:25:30', '10:32:18'],
        '股票': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH', '000858.SZ'],
        '方向': ['买入', '卖出', '买入', '买入', '卖出'],
        '委托价': [12.50, 18.30, 8.90, 45.20, 168.50],
        '委托量': [1000, 500, 1200, 300, 100],
        '成交量': [1000, 500, 800, 0, 100],
        '成交价': [12.48, 18.32, 8.91, 0, 168.45],
        '状态': ['已成交', '已成交', '部分成交', '待成交', '已成交'],
        '策略': ['均线策略', '动量策略', '网格交易', '均线策略', '趋势跟踪']
    })


@st.cache_data(ttl=300)  # 5分钟缓存
def get_order_statistics():
    """获取订单统计数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_trading_data("order_stats")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取订单统计失败: {str(e)}")
    
    # 降级数据
    return {
        "pending": {"value": "3", "delta": "1"},
        "executed": {"value": "22", "delta": "7"},
        "cancelled": {"value": "5", "delta": "2"},
        "partial": {"value": "2", "delta": "0"}
    }


@st.cache_data(ttl=300)  # 5分钟缓存
def get_positions_data():
    """获取持仓数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_portfolio_data("positions")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取持仓数据失败: {str(e)}")
    
    # 降级数据
    return pd.DataFrame({
        '股票代码': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH', '000858.SZ', '002415.SZ'],
        '股票名称': ['平安银行', '万科A', '浦发银行', '招商银行', '五粮液', '海康威视'],
        '持仓数量': [1000, 500, 1200, 300, 100, 800],
        '成本价': [12.20, 18.50, 8.80, 44.50, 165.00, 35.20],
        '最新价': [12.50, 18.30, 8.90, 45.20, 168.50, 36.10],
        '市值': [12500, 9150, 10680, 13560, 16850, 28880],
        '盈亏': [300, -100, 120, 210, 350, 720],
        '盈亏率': ['2.46%', '-1.08%', '1.14%', '1.57%', '2.12%', '2.56%'],
        '持仓比例': ['2.6%', '1.9%', '2.2%', '2.8%', '3.5%', '6.0%']
    })


@st.cache_data(ttl=600)  # 10分钟缓存
def get_trading_history(start_date=None, end_date=None):
    """获取交易历史数据"""
    try:
        data_service = get_data_service()
        params = {}
        if start_date:
            params["start_date"] = start_date.strftime("%Y-%m-%d")
        if end_date:
            params["end_date"] = end_date.strftime("%Y-%m-%d")
        
        result = data_service.get_trading_data("history", params)
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取交易历史失败: {str(e)}")
    
    # 降级数据
    return pd.DataFrame({
        '时间': ['2024-01-15 10:30:15', '2024-01-15 10:28:42', '2024-01-15 10:31:05',
                '2024-01-15 10:25:30', '2024-01-15 10:32:18', '2024-01-14 14:25:10'],
        '股票代码': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH', '000858.SZ', '002415.SZ'],
        '股票名称': ['平安银行', '万科A', '浦发银行', '招商银行', '五粮液', '海康威视'],
        '方向': ['买入', '卖出', '买入', '买入', '卖出', '买入'],
        '成交价': [12.48, 18.32, 8.91, 45.18, 168.45, 35.80],
        '成交量': [1000, 500, 1200, 300, 100, 800],
        '成交金额': [12480, 9160, 10692, 13554, 16845, 28640],
        '手续费': [12.48, 9.16, 10.69, 13.55, 16.85, 28.64],
        '策略': ['均线策略', '动量策略', '网格交易', '均线策略', '趋势跟踪', '手动交易'],
        '备注': ['自动执行', '自动执行', '网格补仓', '自动执行', '止盈卖出', '手动买入']
    })


@st.cache_data(ttl=300)  # 5分钟缓存
def get_risk_monitor_data():
    """获取风险监控数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_risk_data("monitor")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取风险监控数据失败: {str(e)}")
    
    # 降级数据
    return {
        "overview": {
            "total_position_ratio": {"value": "75.2%", "delta": "5.2%"},
            "max_single_position": {"value": "6.0%", "delta": "1.0%"},
            "daily_drawdown": {"value": "-2.1%", "delta": "-0.8%"},
            "risk_score": {"value": "85分", "delta": "5分"}
        },
        "details": pd.DataFrame({
            '风险项目': ['总持仓比例', '单股最大持仓', '行业集中度', '日内亏损', '最大回撤', '杠杆比例'],
            '当前值': ['75.2%', '6.0%', '30.8%', '-2.1%', '-8.5%', '1.2倍'],
            '风险限额': ['80%', '10%', '40%', '-5%', '-15%', '2倍'],
            '使用率': ['94%', '60%', '77%', '42%', '57%', '60%'],
            '风险等级': ['中', '低', '中', '低', '中', '低'],
            '状态': ['正常', '正常', '正常', '正常', '正常', '正常']
        })
    }


def render_trading_monitor_page():
    """渲染交易监控页面"""
    st.title("📊 交易监控")
    
    # 侧边栏导航
    create_sidebar_navigation()
    
    # 创建标签页
    tab1, tab2, tab3, tab4, tab5 = st.tabs([
        "实时监控", "订单管理", "持仓分析", "交易记录", "风险控制"
    ])
    
    with tab1:
        render_realtime_monitor_tab()
    
    with tab2:
        render_order_management_tab()
    
    with tab3:
        render_position_analysis_tab()
    
    with tab4:
        render_trading_history_tab()
    
    with tab5:
        render_risk_control_tab()


def render_realtime_monitor_tab():
    """渲染实时监控标签页"""
    st.header("实时交易监控")
    
    # 获取交易概览数据
    with st.spinner("加载交易概览数据..."):
        overview_data = get_trading_overview()
    
    # 交易概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card(
            "今日交易",
            overview_data.get("today_trades", {}).get("value", "0笔"),
            "💼",
            delta=overview_data.get("today_trades", {}).get("delta", "0"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "成交金额",
            overview_data.get("today_amount", {}).get("value", "0万"),
            "💰",
            delta=overview_data.get("today_amount", {}).get("delta", "0万"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "今日盈亏",
            overview_data.get("today_pnl", {}).get("value", "0万"),
            "📈",
            delta=overview_data.get("today_pnl", {}).get("delta", "0万"),
            delta_color="normal"
        )
    
    with col4:
        create_metric_card(
            "持仓市值",
            overview_data.get("position_value", {}).get("value", "0万"),
            "📊",
            delta=overview_data.get("position_value", {}).get("delta", "0万"),
            delta_color="normal"
        )
    
    st.divider()
    
    # 实时行情监控
    st.subheader("重点关注股票")
    
    # 获取关注股票数据
    with st.spinner("加载关注股票数据..."):
        watchlist = get_watchlist_data()
    
    create_data_table(watchlist, "重点关注")
    
    # 实时K线图
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("实时K线 - 平安银行")
        
        # 获取K线数据
        with st.spinner("加载K线数据..."):
            kline_data = get_realtime_kline("000001.SZ")
        
        create_candlestick_chart(
            kline_data,
            title="平安银行 5分钟K线",
            height=300
        )
    
    with col2:
        st.subheader("实时盈亏曲线")
        
        # 获取盈亏数据
        with st.spinner("加载盈亏数据..."):
            pnl_data = get_realtime_pnl()
        
        create_line_chart(
            pnl_data,
            x_col='时间',
            y_col='累计盈亏',
            title="今日累计盈亏",
            height=300
        )
    
    # 交易信号监控
    st.subheader("交易信号监控")
    
    # 获取交易信号数据
    with st.spinner("加载交易信号..."):
        signals = get_trading_signals()
    
    create_data_table(signals, "最新交易信号")
    
    # 自动刷新控制
    col1, col2, col3 = st.columns(3)
    
    with col1:
        auto_refresh = st.checkbox("自动刷新", value=True)
    
    with col2:
        refresh_interval = st.selectbox("刷新间隔", ["1秒", "5秒", "10秒", "30秒"], index=2)
    
    with col3:
        if st.button("立即刷新"):
            st.rerun()


def render_order_management_tab():
    """渲染订单管理标签页"""
    st.header("订单管理")
    
    # 获取订单统计数据
    with st.spinner("加载订单统计..."):
        order_stats = get_order_statistics()
    
    # 订单概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card(
            "待处理",
            order_stats.get("pending", {}).get("value", "0"),
            "⏳",
            delta=order_stats.get("pending", {}).get("delta", "0"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "已成交",
            order_stats.get("executed", {}).get("value", "0"),
            "✅",
            delta=order_stats.get("executed", {}).get("delta", "0"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "已撤销",
            order_stats.get("cancelled", {}).get("value", "0"),
            "❌",
            delta=order_stats.get("cancelled", {}).get("delta", "0"),
            delta_color="normal"
        )
    
    with col4:
        create_metric_card(
            "部分成交",
            order_stats.get("partial", {}).get("value", "0"),
            "🔄",
            delta=order_stats.get("partial", {}).get("delta", "0"),
            delta_color="normal"
        )
    
    st.divider()
    
    # 订单列表
    st.subheader("当前订单")
    
    # 获取订单数据
    with st.spinner("加载订单数据..."):
        orders = get_orders_data()
    
    # 订单过滤
    col1, col2, col3 = st.columns(3)
    
    with col1:
        status_filter = create_multiselect_filter(
            orders, '状态', '订单状态', key='order_status'
        )
    
    with col2:
        direction_filter = create_multiselect_filter(
            orders, '方向', '交易方向', key='order_direction'
        )
    
    with col3:
        strategy_filter = create_multiselect_filter(
            orders, '策略', '策略筛选', key='order_strategy'
        )
    
    # 应用过滤器
    filtered_orders = orders.copy()
    if status_filter:
        filtered_orders = filtered_orders[filtered_orders['状态'].isin(status_filter)]
    if direction_filter:
        filtered_orders = filtered_orders[filtered_orders['方向'].isin(direction_filter)]
    if strategy_filter:
        filtered_orders = filtered_orders[filtered_orders['策略'].isin(strategy_filter)]
    
    create_data_table(filtered_orders, "订单详情")
    
    # 订单操作
    st.subheader("订单操作")
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        if st.button("📝 手动下单", use_container_width=True):
            st.session_state.show_manual_order = True
    
    with col2:
        if st.button("❌ 批量撤单", use_container_width=True):
            st.session_state.show_batch_cancel = True
    
    with col3:
        if st.button("🔄 订单修改", use_container_width=True):
            st.session_state.show_order_modify = True
    
    with col4:
        if st.button("📊 订单分析", use_container_width=True):
            st.session_state.show_order_analysis = True
    
    # 手动下单对话框
    if st.session_state.get('show_manual_order', False):
        render_manual_order_dialog()
    
    # 订单分析
    if st.session_state.get('show_order_analysis', False):
        render_order_analysis()


def render_manual_order_dialog():
    """渲染手动下单对话框"""
    with st.expander("手动下单", expanded=True):
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("基本信息")
            symbol = st.text_input("股票代码", placeholder="例: 000001.SZ")
            direction = st.selectbox("交易方向", ["买入", "卖出"])
            order_type = st.selectbox("订单类型", ["限价单", "市价单", "止损单", "止盈单"])
        
        with col2:
            st.subheader("价格数量")
            if order_type != "市价单":
                price = st.number_input("委托价格", min_value=0.01, value=10.0, step=0.01)
            quantity = st.number_input("委托数量", min_value=100, value=1000, step=100)
            
            # 计算委托金额
            if order_type != "市价单":
                amount = price * quantity
                st.info(f"委托金额: {amount:,.2f} 元")
        
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("高级设置")
            strategy_source = st.selectbox("策略来源", ["手动交易", "均线策略", "动量策略", "网格交易"])
            valid_time = st.selectbox("有效期", ["当日有效", "本周有效", "长期有效"])
        
        with col2:
            st.subheader("风险控制")
            enable_stop_loss = st.checkbox("启用止损")
            if enable_stop_loss:
                stop_loss_price = st.number_input("止损价格", min_value=0.01, value=9.0)
            
            enable_take_profit = st.checkbox("启用止盈")
            if enable_take_profit:
                take_profit_price = st.number_input("止盈价格", min_value=0.01, value=11.0)
        
        # 下单按钮
        col1, col2, col3 = st.columns(3)
        
        with col1:
            if st.button("确认下单", type="primary"):
                if symbol and quantity > 0:
                    show_success_message(f"订单提交成功: {direction} {symbol} {quantity}股")
                    st.session_state.show_manual_order = False
                    st.rerun()
                else:
                    show_error_message("请填写完整的订单信息")
        
        with col2:
            if st.button("预览订单"):
                if symbol and quantity > 0:
                    st.info(f"订单预览: {direction} {symbol} {quantity}股 @ {price if order_type != '市价单' else '市价'}")
        
        with col3:
            if st.button("取消"):
                st.session_state.show_manual_order = False
                st.rerun()


def render_order_analysis():
    """渲染订单分析"""
    with st.expander("订单分析", expanded=True):
        # 获取订单分析数据
        with st.spinner("加载订单分析数据..."):
            try:
                data_service = get_data_service()
                analysis_result = data_service.get_trading_data("order_analysis")
                if analysis_result and analysis_result.get("success"):
                    analysis_data = analysis_result.get("data", {})
                else:
                    # 使用降级数据
                    analysis_data = {
                        "execution_stats": pd.DataFrame({
                            '指标': ['总订单数', '成交订单', '撤销订单', '部分成交', '成交率'],
                            '今日': ['32', '22', '5', '2', '68.8%'],
                            '本周': ['156', '128', '18', '8', '82.1%'],
                            '本月': ['678', '589', '65', '24', '86.8%']
                        }),
                        "price_analysis": pd.DataFrame({
                            '股票': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH'],
                            '委托价': [12.50, 18.30, 8.90, 45.20],
                            '成交价': [12.48, 18.32, 8.91, 45.18],
                            '价格偏差': ['-0.02', '+0.02', '+0.01', '-0.02'],
                            '偏差率': ['-0.16%', '+0.11%', '+0.11%', '-0.04%']
                        }),
                        "time_distribution": pd.DataFrame({
                            '时间段': ['09:30-10:00', '10:00-10:30', '10:30-11:00', '11:00-11:30', '13:00-13:30', '13:30-14:00', '14:00-14:30', '14:30-15:00'],
                            '订单数量': [5, 8, 12, 6, 4, 7, 9, 3],
                            '成交数量': [4, 7, 10, 5, 3, 6, 8, 3],
                            '成交率': ['80%', '87.5%', '83.3%', '83.3%', '75%', '85.7%', '88.9%', '100%']
                        })
                    }
            except Exception as e:
                st.error(f"获取订单分析数据失败: {str(e)}")
                # 使用降级数据
                analysis_data = {
                    "execution_stats": pd.DataFrame({
                        '指标': ['总订单数', '成交订单', '撤销订单', '部分成交', '成交率'],
                        '今日': ['32', '22', '5', '2', '68.8%'],
                        '本周': ['156', '128', '18', '8', '82.1%'],
                        '本月': ['678', '589', '65', '24', '86.8%']
                    }),
                    "price_analysis": pd.DataFrame({
                        '股票': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH'],
                        '委托价': [12.50, 18.30, 8.90, 45.20],
                        '成交价': [12.48, 18.32, 8.91, 45.18],
                        '价格偏差': ['-0.02', '+0.02', '+0.01', '-0.02'],
                        '偏差率': ['-0.16%', '+0.11%', '+0.11%', '-0.04%']
                    }),
                    "time_distribution": pd.DataFrame({
                        '时间段': ['09:30-10:00', '10:00-10:30', '10:30-11:00', '11:00-11:30', '13:00-13:30', '13:30-14:00', '14:00-14:30', '14:30-15:00'],
                        '订单数量': [5, 8, 12, 6, 4, 7, 9, 3],
                        '成交数量': [4, 7, 10, 5, 3, 6, 8, 3],
                        '成交率': ['80%', '87.5%', '83.3%', '83.3%', '75%', '85.7%', '88.9%', '100%']
                    })
                }
        
        # 订单统计
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("订单成交分析")
            create_data_table(analysis_data.get("execution_stats", pd.DataFrame()))
        
        with col2:
            st.subheader("成交价格分析")
            create_data_table(analysis_data.get("price_analysis", pd.DataFrame()))
        
        # 订单时间分析
        st.subheader("订单时间分布")
        
        time_dist_data = analysis_data.get("time_distribution", pd.DataFrame())
        if not time_dist_data.empty:
            create_bar_chart(
                time_dist_data,
                x_col='时间段',
                y_col='订单数量',
                title="订单时间分布",
                height=300
            )
        
        if st.button("关闭分析"):
            st.session_state.show_order_analysis = False
            st.rerun()


def render_position_analysis_tab():
    """渲染持仓分析标签页"""
    st.header("持仓分析")
    
    # 获取持仓数据
    with st.spinner("加载持仓数据..."):
        positions_data = get_positions_data()
    
    # 持仓概览 - 使用真实数据计算
    if not positions_data.empty:
        total_positions = len(positions_data)
        total_value = positions_data['市值'].sum() / 10000  # 转换为万元
        total_pnl = positions_data['盈亏'].sum() / 10000  # 转换为万元
        position_ratio = "75.2%"  # 这个需要从组合总资产计算，暂时使用固定值
        
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            create_metric_card("持仓股票", f"{total_positions}只", "📊", delta="2", delta_color="normal")
        
        with col2:
            create_metric_card("持仓市值", f"{total_value:.1f}万", "💰", delta="15.6万", delta_color="normal")
        
        with col3:
            pnl_sign = "+" if total_pnl >= 0 else ""
            create_metric_card("浮动盈亏", f"{pnl_sign}{total_pnl:.1f}万", "📈", delta="8.3万", delta_color="normal")
        
        with col4:
            create_metric_card("持仓比例", position_ratio, "📋", delta="5.2%", delta_color="normal")
    else:
        # 降级显示
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            create_metric_card("持仓股票", "15只", "📊", delta="2", delta_color="normal")
        with col2:
            create_metric_card("持仓市值", "485.2万", "💰", delta="15.6万", delta_color="normal")
        with col3:
            create_metric_card("浮动盈亏", "+25.8万", "📈", delta="8.3万", delta_color="normal")
        with col4:
            create_metric_card("持仓比例", "75.2%", "📋", delta="5.2%", delta_color="normal")
    
    st.divider()
    
    # 持仓明细
    st.subheader("持仓明细")
    
    # 获取持仓明细数据
    with st.spinner("加载持仓明细..."):
        try:
            data_service = get_data_service()
            detail_result = data_service.get_portfolio_data("position_details")
            if detail_result and detail_result.get("success"):
                detail_data = detail_result.get("data", pd.DataFrame())
                if isinstance(detail_data, dict):
                    detail_data = pd.DataFrame(detail_data)
            else:
                # 使用已获取的持仓数据作为降级
                detail_data = positions_data
        except Exception as e:
            st.error(f"获取持仓明细失败: {str(e)}")
            # 使用已获取的持仓数据作为降级
            detail_data = positions_data
    
    create_data_table(detail_data, "持仓详情")
    
    # 持仓分析图表
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("持仓分布")
        
        # 按市值分布
        if not detail_data.empty:
            create_bar_chart(
                detail_data.head(6),
                x_col='股票名称',
                y_col='市值',
                title="持仓市值分布",
                height=300
            )
    
    with col2:
        st.subheader("盈亏分布")
        
        # 按盈亏分布
        if not detail_data.empty:
            create_bar_chart(
                detail_data.head(6),
                x_col='股票名称',
                y_col='盈亏',
                title="持仓盈亏分布",
                height=300
            )
    
    # 行业分布
    st.subheader("行业分布分析")
    
    # 获取行业分布数据
    with st.spinner("加载行业分布..."):
        try:
            data_service = get_data_service()
            industry_result = data_service.get_portfolio_data("industry_distribution")
            if industry_result and industry_result.get("success"):
                industry_data = industry_result.get("data", pd.DataFrame())
                if isinstance(industry_data, dict):
                    industry_data = pd.DataFrame(industry_data)
            else:
                # 使用降级数据
                industry_data = pd.DataFrame({
                    '行业': ['银行', '房地产', '食品饮料', '电子', '医药', '其他'],
                    '持仓数量': [3, 1, 1, 2, 1, 2],
                    '市值': [36740, 9150, 16850, 28880, 12500, 15000],
                    '占比': ['30.8%', '7.7%', '14.1%', '24.2%', '10.5%', '12.6%'],
                    '盈亏': [630, -100, 350, 720, 300, 200]
                })
        except Exception as e:
            st.error(f"获取行业分布失败: {str(e)}")
            # 使用降级数据
            industry_data = pd.DataFrame({
                '行业': ['银行', '房地产', '食品饮料', '电子', '医药', '其他'],
                '持仓数量': [3, 1, 1, 2, 1, 2],
                '市值': [36740, 9150, 16850, 28880, 12500, 15000],
                '占比': ['30.8%', '7.7%', '14.1%', '24.2%', '10.5%', '12.6%'],
                '盈亏': [630, -100, 350, 720, 300, 200]
            })
    
    col1, col2 = st.columns(2)
    
    with col1:
        if not industry_data.empty:
            create_bar_chart(
                industry_data,
                x_col='行业',
                y_col='市值',
                title="行业市值分布",
                height=300
            )
    
    with col2:
        if not industry_data.empty:
            create_bar_chart(
                industry_data,
                x_col='行业',
                y_col='盈亏',
                title="行业盈亏分布",
                height=300
            )


def render_trading_history_tab():
    """渲染交易记录标签页"""
    st.header("交易记录")
    
    # 获取交易统计数据
    with st.spinner("加载交易统计..."):
        try:
            data_service = get_data_service()
            stats_result = data_service.get_trading_data("daily_stats")
            if stats_result and stats_result.get("success"):
                stats_data = stats_result.get("data", {})
            else:
                # 使用降级数据
                stats_data = {
                    "today_trades": {"value": "25笔", "delta": "8"},
                    "today_amount": {"value": "125.8万", "delta": "35.2万"},
                    "today_fees": {"value": "1258元", "delta": "352元"},
                    "today_net_pnl": {"value": "+11.2万", "delta": "7.9万"}
                }
        except Exception as e:
            st.error(f"获取交易统计失败: {str(e)}")
            # 使用降级数据
            stats_data = {
                "today_trades": {"value": "25笔", "delta": "8"},
                "today_amount": {"value": "125.8万", "delta": "35.2万"},
                "today_fees": {"value": "1258元", "delta": "352元"},
                "today_net_pnl": {"value": "+11.2万", "delta": "7.9万"}
            }
    
    # 交易统计
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card(
            "今日交易",
            stats_data.get("today_trades", {}).get("value", "0笔"),
            "📊",
            delta=stats_data.get("today_trades", {}).get("delta", "0"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "成交金额",
            stats_data.get("today_amount", {}).get("value", "0万"),
            "💰",
            delta=stats_data.get("today_amount", {}).get("delta", "0万"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "手续费",
            stats_data.get("today_fees", {}).get("value", "0元"),
            "💳",
            delta=stats_data.get("today_fees", {}).get("delta", "0元"),
            delta_color="inverse"
        )
    
    with col4:
        create_metric_card(
            "净盈亏",
            stats_data.get("today_net_pnl", {}).get("value", "0万"),
            "📈",
            delta=stats_data.get("today_net_pnl", {}).get("delta", "0万"),
            delta_color="normal"
        )
    
    st.divider()
    
    # 时间筛选
    col1, col2, col3 = st.columns(3)
    
    with col1:
        start_date, end_date = create_date_filter("查询时间范围")
    
    with col2:
        trade_type = st.selectbox("交易类型", ["全部", "买入", "卖出"])
    
    with col3:
        symbol_filter = st.text_input("股票代码筛选", placeholder="例: 000001")
    
    # 交易记录表
    st.subheader("交易明细")
    
    # 获取交易记录数据
    with st.spinner("加载交易记录..."):
        trades = get_trading_history(start_date, end_date)
    
    create_data_table(trades, "交易记录")
    
    # 交易分析
    st.subheader("交易分析")
    
    # 获取交易分析数据
    with st.spinner("加载交易分析数据..."):
        try:
            data_service = get_data_service()
            analysis_result = data_service.get_trading_data("analysis")
            if analysis_result and analysis_result.get("success"):
                analysis_data = analysis_result.get("data", {})
            else:
                # 使用降级数据
                analysis_data = {
                    "daily_volume": pd.DataFrame({
                        '日期': pd.date_range(start='2024-01-10', end='2024-01-15', freq='D'),
                        '交易笔数': [15, 18, 22, 20, 25, 28],
                        '交易金额': [85.2, 92.5, 108.3, 95.7, 125.8, 142.6]
                    }),
                    "strategy_trades": pd.DataFrame({
                        '策略': ['均线策略', '动量策略', '网格交易', '趋势跟踪', '手动交易'],
                        '交易次数': [8, 6, 5, 4, 2],
                        '成交金额': [45.2, 32.8, 28.5, 15.3, 8.0]
                    })
                }
        except Exception as e:
            st.error(f"获取交易分析数据失败: {str(e)}")
            # 使用降级数据
            analysis_data = {
                "daily_volume": pd.DataFrame({
                    '日期': pd.date_range(start='2024-01-10', end='2024-01-15', freq='D'),
                    '交易笔数': [15, 18, 22, 20, 25, 28],
                    '交易金额': [85.2, 92.5, 108.3, 95.7, 125.8, 142.6]
                }),
                "strategy_trades": pd.DataFrame({
                    '策略': ['均线策略', '动量策略', '网格交易', '趋势跟踪', '手动交易'],
                    '交易次数': [8, 6, 5, 4, 2],
                    '成交金额': [45.2, 32.8, 28.5, 15.3, 8.0]
                })
            }
    
    col1, col2 = st.columns(2)
    
    with col1:
        # 每日交易量
        daily_volume = analysis_data.get("daily_volume", pd.DataFrame())
        if not daily_volume.empty:
            create_line_chart(
                daily_volume,
                x_col='日期',
                y_col='交易金额',
                title="每日交易金额趋势",
                height=300
            )
    
    with col2:
        # 策略交易分布
        strategy_trades = analysis_data.get("strategy_trades", pd.DataFrame())
        if not strategy_trades.empty:
            create_bar_chart(
                strategy_trades,
                x_col='策略',
                y_col='交易次数',
                title="策略交易次数分布",
                height=300
            )


def render_risk_control_tab():
    """渲染风险控制标签页"""
    st.header("风险控制")
    
    # 获取风险概览数据
    with st.spinner("加载风险概览..."):
        risk_data = get_risk_monitor_data()
    
    # 风险指标概览
    overview_data = risk_data.get("overview", {})
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card(
            "总持仓比例",
            overview_data.get("total_position_ratio", {}).get("value", "75.2%"),
            "📊",
            delta=overview_data.get("total_position_ratio", {}).get("delta", "5.2%"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "最大单仓",
            overview_data.get("max_single_position", {}).get("value", "6.0%"),
            "⚠️",
            delta=overview_data.get("max_single_position", {}).get("delta", "1.0%"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "日内回撤",
            overview_data.get("daily_drawdown", {}).get("value", "-2.1%"),
            "📉",
            delta=overview_data.get("daily_drawdown", {}).get("delta", "-0.8%"),
            delta_color="inverse"
        )
    
    with col4:
        create_metric_card(
            "风险评分",
            overview_data.get("risk_score", {}).get("value", "85分"),
            "🛡️",
            delta=overview_data.get("risk_score", {}).get("delta", "5分"),
            delta_color="normal"
        )
    
    st.divider()
    
    # 风险限额设置
    st.subheader("风险限额设置")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("持仓风险")
        max_position_ratio = st.slider("最大持仓比例(%)", 50, 100, 80)
        max_single_position = st.slider("单个股票最大持仓(%)", 1, 20, 10)
        max_industry_position = st.slider("单个行业最大持仓(%)", 10, 50, 30)
    
    with col2:
        st.subheader("交易风险")
        max_daily_loss = st.slider("日最大亏损限额(%)", 1, 10, 5)
        max_drawdown = st.slider("最大回撤限额(%)", 5, 20, 10)
        stop_loss_ratio = st.slider("止损比例(%)", 1, 10, 3)
    
    # 风险监控表
    st.subheader("风险监控")
    
    # 获取风险监控数据
    with st.spinner("加载风险监控数据..."):
        risk_data = get_risk_monitor_data()
    
    risk_monitor = risk_data.get("details", pd.DataFrame({
        '风险项目': ['总持仓比例', '单股最大持仓', '行业集中度', '日内亏损', '最大回撤', '杠杆比例'],
        '当前值': ['75.2%', '6.0%', '30.8%', '-2.1%', '-8.5%', '1.2倍'],
        '风险限额': ['80%', '10%', '40%', '-5%', '-15%', '2倍'],
        '使用率': ['94%', '60%', '77%', '42%', '57%', '60%'],
        '风险等级': ['中', '低', '中', '低', '中', '低'],
        '状态': ['正常', '正常', '正常', '正常', '正常', '正常']
    }))
    
    create_data_table(risk_monitor, "风险监控详情")
    
    # 风险告警设置
    st.subheader("风险告警设置")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("告警阈值")
        position_alert = st.slider("持仓告警阈值(%)", 70, 95, 85)
        loss_alert = st.slider("亏损告警阈值(%)", 1, 10, 3)
        drawdown_alert = st.slider("回撤告警阈值(%)", 5, 20, 8)
    
    with col2:
        st.subheader("告警方式")
        email_alert = st.checkbox("邮件告警", value=True)
        sms_alert = st.checkbox("短信告警", value=False)
        system_alert = st.checkbox("系统弹窗", value=True)
    
    if st.button("保存风险设置"):
        show_success_message("风险控制设置已保存")